import React, { useState, useEffect } from 'react';
import { request } from '../utils/axios';

interface User {
  _id: string;
  name: string;
  roles: string;
  lastLogin: string;
  status: number;
  cate?: any[];
  role_id?: string; // 新增role_id字段
}

interface Role {
  _id: string;
  name: string;
  permissions: any[];
  description: string;
}

interface MenuItem {
  _id: string;
  title: string;
  path: string;
  icon: string;
  parentId: string;
}

const Authority: React.FC = () => {
  // 获取当前登录用户信息
  const authStorage = JSON.parse(localStorage.getItem('auth-storage') || '{}');
  const currentUser = authStorage.state || {};
  console.log(currentUser,33);
  
  const user = JSON.parse(localStorage.getItem('user') || '{}');
  const roleId = user.role_id?._id;
  // console.log(roleId);
  
  const [activeTab, setActiveTab] = useState<'users' | 'roles' | 'menus'>('users');
  const [users, setUsers] = useState<User[]>([]);
  const [roles, setRoles] = useState<Role[]>([]);
  const [menus, setMenus] = useState<MenuItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string>('');
  
  // 编辑用户相关状态
  const [showEditModal, setShowEditModal] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [editForm, setEditForm] = useState({
    name: '',
    role_id: '',
    status: 1
  });

  // 编辑角色相关状态
  const [showRoleEditModal, setShowRoleEditModal] = useState(false);
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [roleEditForm, setRoleEditForm] = useState({
    name: ''
  });

  // 搜索用户相关状态
  const [searchName, setSearchName] = useState('');

  // 添加用户相关状态
  const [showAddModal, setShowAddModal] = useState(false);
  const [addForm, setAddForm] = useState({
    name: '',
    roles: '',
    status: 1
  });

  // 拉取所有角色名全集
  const [allRoleNames, setAllRoleNames] = useState<string[]>([]);

  // 添加角色相关状态
  const [showAddRoleModal, setShowAddRoleModal] = useState(false);
  const [addRoleForm, setAddRoleForm] = useState({
    name: '',
    permissions: [] as string[],
    description: ''
  });
  const [allMenus, setAllMenus] = useState<MenuItem[]>([]);

  // 获取用户列表
  const fetchUsers = async (search = '') => {
    try {
      setLoading(true);
      setError('');
      const response = await request({
        url: '/YSK/users' + (search ? `?name=${encodeURIComponent(search)}` : ''),
        method: 'GET'
      });
      if (response.code === 200) {
        setUsers(response.data);
      } else {
        setError(response.message || '获取用户列表失败');
      }
    } catch (err: any) {
      setError('获取用户列表失败: ' + (err.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  // 获取角色列表
  const fetchRoles = async () => {
    try {
      setLoading(true);
      setError('');
      const response = await request({
        url: '/YSK/roles',
        method: 'GET'
      });
      if (response.code === 200) {
        setRoles(response.data);
      } else {
        setError(response.message || '获取角色列表失败');
      }
    } catch (err: any) {
      setError('获取角色列表失败: ' + (err.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  // 获取菜单列表
  const fetchMenus = async () => {
    try {
      setLoading(true);
      setError('');
      const response = await request({
        url: '/YSK/menu',
        method: 'GET'
      });
      if (response.code === 200) {
        setMenus(response.data);
      } else {
        setError(response.message || '获取菜单列表失败');
      }
    } catch (err: any) {
      setError('获取菜单列表失败: ' + (err.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  // 拉取所有菜单
  const fetchAllMenus = async () => {
    try {
      const response = await request({ url: '/YSK/menu', method: 'GET' });
      if (response.code === 200) setAllMenus(response.data);
    } catch {}
  };

  // 打开编辑用户弹窗
  const handleEditUser = (user: User) => {
    setEditingUser(user);
    setEditForm({
      name: user.name,
      role_id: user.role_id || '',
      status: user.status
    });
    fetchRoles(); // 保证弹窗打开时拉取角色
    setShowEditModal(true);
  };

  // 关闭编辑弹窗
  const handleCloseEditModal = () => {
    setShowEditModal(false);
    setEditingUser(null);
    setEditForm({
      name: '',
      role_id: '',
      status: 1
    });
  };

  // 更新用户信息
  const handleUpdateUser = async () => {
    if (!editingUser) return;
    
    try {
      setLoading(true);
      setError('');
      const response = await request({
        url: '/YSK/updateUser',
        method: 'POST',
        data: {
          id: editingUser._id,
          name: editForm.name,
          role_id: editForm.role_id,
          status: editForm.status
        }
      });
      
      if (response.code === 200) {
        // 更新本地用户列表
        setUsers(users.map(user => 
          user._id === editingUser._id 
            ? { ...user, ...editForm }
            : user
        ));
        handleCloseEditModal();
      } else {
        setError(response.message || '更新用户失败');
      }
    } catch (err: any) {
      setError('更新用户失败: ' + (err.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  // 打开编辑角色弹窗
  const handleEditRole = (role: Role) => {
    setEditingRole(role);
    setRoleEditForm({ name: role.name });
    setShowRoleEditModal(true);
  };

  // 关闭编辑角色弹窗
  const handleCloseRoleEditModal = () => {
    setShowRoleEditModal(false);
    setEditingRole(null);
    setRoleEditForm({ name: '' });
  };

  // 更新角色信息（只允许编辑名称）
  const handleUpdateRole = async () => {
    if (!editingRole) return;
    try {
      setLoading(true);
      setError('');
      const response = await request({
        url: '/YSK/updateRole',
        method: 'POST',
        data: { id: editingRole._id, name: roleEditForm.name }
      });
      if (response.code === 200) {
        await fetchRoles();
        handleCloseRoleEditModal();
      } else {
        setError(response.message || '更新角色失败');
      }
    } catch (err: any) {
      setError('更新角色失败: ' + (err.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  // 搜索按钮点击
  const handleSearch = () => {
    fetchUsers(searchName);
  };

  // 删除用户
  const handleDeleteUser = async (id: string) => {
    if (!window.confirm('确定要删除该用户吗？')) return;
    try {
      setLoading(true);
      setError('');
      const response = await request({
        url: '/YSK/deleteUser',
        method: 'POST',
        data: { id }
      });
      if (response.code === 200) {
        setUsers(users.filter(user => user._id !== id));
      } else {
        setError(response.message || '删除用户失败');
      }
    } catch (err: any) {
      setError('删除用户失败: ' + (err.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  // 打开添加用户弹窗
  const handleOpenAddModal = () => {
    setAddForm({ name: '', roles: '', status: 1 });
    setShowAddModal(true);
  };

  // 关闭添加用户弹窗
  const handleCloseAddModal = () => {
    setShowAddModal(false);
  };

  // 添加用户
  const handleAddUser = async () => {
    try {
      setLoading(true);
      setError('');
      const response = await request({
        url: '/YSK/addUser',
        method: 'POST',
        data: addForm
      });
      if (response.code === 200) {
        setUsers([response.data, ...users]);
        handleCloseAddModal();
      } else {
        setError(response.message || '添加用户失败');
      }
    } catch (err: any) {
      setError('添加用户失败: ' + (err.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  // 打开添加角色弹窗
  const handleOpenAddRoleModal = () => {
    setAddRoleForm({ name: '', permissions: [], description: '' });
    fetchAllMenus();
    setShowAddRoleModal(true);
  };
  // 关闭弹窗
  const handleCloseAddRoleModal = () => setShowAddRoleModal(false);

  // 提交添加角色
  const handleAddRole = async () => {
    if (!addRoleForm.name) return alert('请输入角色名称');
    try {
      const response = await request({
        url: '/YSK/addRole',
        method: 'POST',
        data: addRoleForm
      });
      if (response.code === 200) {
        await fetchRoles();
        setShowAddRoleModal(false);
      } else {
        alert(response.message || '添加失败');
      }
    } catch (err: any) {
      alert('添加失败: ' + (err.message || '未知错误'));
    }
  };

  // 根据当前激活的标签页获取对应数据
  useEffect(() => {
    switch (activeTab) {
      case 'users':
        fetchUsers();
        break;
      case 'roles':
        fetchRoles();
        break;
      case 'menus':
        fetchMenus();
        break;
    }
    // eslint-disable-next-line
  }, [activeTab]);

  // 页面初始化时拉取角色列表，保证下拉框有数据
  useEffect(() => {
    fetchRoles();
  }, []);

  // 拉取所有角色名全集
  useEffect(() => {
    // 只要 roles 变化就更新全集
    setAllRoleNames(Array.from(new Set(roles.map(role => role.name))));
  }, [roles]);

  // 格式化状态显示
  const getStatusText = (status: number) => {
    return status === 1 ? '正常' : '异常';
  };

  // 格式化日期显示
  const formatDate = (dateString: string) => {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN');
  };

  return (
    <div className="page-container">
      <h1>权限管理</h1>
      
      <div className="tabs">
        <button 
          className={`tab ${activeTab === 'users' ? 'active' : ''}`} 
          onClick={() => setActiveTab('users')}
        >
          用户管理
        </button>
        {/* 只有超级管理员能看到角色管理Tab */}
        {roleId === '687224bbe90bf94faaf6e00a' && (
          <button 
            className={`tab ${activeTab === 'roles' ? 'active' : ''}`} 
            onClick={() => setActiveTab('roles')}
          >
            角色管理
          </button>
        )}
        <button 
          className={`tab ${activeTab === 'menus' ? 'active' : ''}`} 
          onClick={() => setActiveTab('menus')}
        >
          菜单管理
        </button>
      </div>

      {error && (
        <div className="error-message" style={{ color: 'red', margin: '10px 0' }}>
          {error}
        </div>
      )}

      {activeTab === 'users' && (
        <div className="tab-content">
          <div className="actions-bar">
            <button className="btn btn-primary" onClick={handleOpenAddModal}>添加用户</button>
            <div className="search-box">
              <input
                type="text"
                placeholder="搜索用户..."
                value={searchName}
                onChange={e => setSearchName(e.target.value)}
                onKeyDown={e => { if (e.key === 'Enter') handleSearch(); }}
              />
              <button onClick={handleSearch}>搜索</button>
            </div>
          </div>
          <div className="table-container">
            <table className="data-table">
              <thead>
                <tr>
                  <th>用户名</th>
                  <th>角色</th>
                  <th>上次登录</th>
                  <th>状态</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {users.map(user => (
                  <tr key={user._id}>
                    <td>{user.name}</td>
                    <td>{roles.find(role => role._id === user.role_id)?.name || '-'}</td>
                    <td>{formatDate(user.lastLogin)}</td>
                    <td>
                      <span className={`status-badge ${user.status === 1 ? 'active' : 'inactive'}`}>
                        {getStatusText(user.status)}
                      </span>
                    </td>
                    <td>
                      <button 
                        className="btn btn-edit" 
                        onClick={() => handleEditUser(user)}
                      >
                        编辑
                      </button>
                      <button className="btn btn-delete" onClick={() => handleDeleteUser(user._id)}>删除</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {activeTab === 'roles' && (
        <div className="tab-content">
          <div className="actions-bar">
            <button className="btn btn-primary" onClick={handleOpenAddRoleModal}>添加角色</button>
          </div>
          <div className="table-container">
            <table className="data-table">
              <thead>
                <tr>
                  <th>角色名称</th>
                  <th>权限数量</th>
                  <th>描述</th>
                </tr>
              </thead>
              <tbody>
                {roles.map(role => (
                  <tr key={role._id}>
                    <td>{role.name}</td>
                    <td>
                      <span className="permission-badge">
                        {role.permissions?.length || 0} 个权限
                      </span>
                    </td>
                    <td>{role.description}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          {/* 添加角色弹窗 */}
          {showAddRoleModal && (
            <div className="modal-overlay" style={{
              position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
              backgroundColor: 'rgba(0,0,0,0.5)', display: 'flex', justifyContent: 'center', alignItems: 'center', zIndex: 1000
            }}>
              <div className="modal-content" style={{ backgroundColor: 'white', padding: 20, borderRadius: 8, minWidth: 400, maxWidth: 500 }}>
                <h3>添加角色</h3>
                <div style={{ marginBottom: 15 }}>
                  <label style={{ display: 'block', marginBottom: 5 }}>角色名称:</label>
                  <input
                    type="text"
                    value={addRoleForm.name}
                    onChange={e => setAddRoleForm({ ...addRoleForm, name: e.target.value })}
                    style={{ width: '100%', padding: 8, border: '1px solid #ddd', borderRadius: 4 }}
                  />
                </div>
                <div style={{ marginBottom: 15 }}>
                  <label style={{ display: 'block', marginBottom: 5 }}>权限选择（已选{addRoleForm.permissions.length}个）:</label>
                  <select
                    multiple
                    value={addRoleForm.permissions}
                    onChange={e => {
                      const selected = Array.from(e.target.selectedOptions).map(opt => opt.value);
                      setAddRoleForm({ ...addRoleForm, permissions: selected });
                    }}
                    style={{ width: '100%', padding: 8, border: '1px solid #ddd', borderRadius: 4, minHeight: 80 }}
                  >
                    {allMenus.map(menu => (
                      <option key={menu._id} value={menu._id}>{menu.title}（{menu._id}）</option>
                    ))}
                  </select>
                </div>
                <div style={{ marginBottom: 20 }}>
                  <label style={{ display: 'block', marginBottom: 5 }}>描述:</label>
                  <input
                    type="text"
                    value={addRoleForm.description}
                    onChange={e => setAddRoleForm({ ...addRoleForm, description: e.target.value })}
                    style={{ width: '100%', padding: 8, border: '1px solid #ddd', borderRadius: 4 }}
                  />
                </div>
                <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
                  <button
                    onClick={handleCloseAddRoleModal}
                    style={{ padding: '8px 16px', border: '1px solid #ddd', borderRadius: 4, backgroundColor: '#f5f5f5', cursor: 'pointer' }}
                  >取消</button>
                  <button
                    onClick={handleAddRole}
                    style={{ padding: '8px 16px', border: 'none', borderRadius: 4, backgroundColor: '#007bff', color: 'white', cursor: 'pointer' }}
                  >保存</button>
                </div>
              </div>
            </div>
          )}
        </div>
      )}

      {activeTab === 'menus' && (
        <div className="tab-content">
          <div className="actions-bar">
            <button className="btn btn-primary">添加菜单</button>
          </div>
          <div className="table-container">
            <table className="data-table">
              <thead>
                <tr>
                  <th>菜单名称</th>
                  <th>路径</th>
                  <th>图标</th>
                  <th>父级ID</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {menus.map(menu => (
                  <tr key={menu._id}>
                    <td>{menu.title}</td>
                    <td>{menu.path}</td>
                    <td>{menu.icon}</td>
                    <td>{menu.parentId || '-'}</td>
                    <td>
                      <button className="btn btn-edit">编辑</button>
                      <button className="btn btn-delete">删除</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* 编辑用户弹窗 */}
      {showEditModal && (
        <div className="modal-overlay" style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          zIndex: 1000
        }}>
          <div className="modal-content" style={{
            backgroundColor: 'white',
            padding: '20px',
            borderRadius: '8px',
            minWidth: '400px',
            maxWidth: '500px'
          }}>
            <h3>编辑用户</h3>
            <div style={{ marginBottom: '15px' }}>
              <label style={{ display: 'block', marginBottom: '5px' }}>用户名:</label>
              <input
                type="text"
                value={editForm.name}
                onChange={(e) => setEditForm({...editForm, name: e.target.value})}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #ddd',
                  borderRadius: '4px'
                }}
              />
            </div>
            
            <div style={{ marginBottom: '15px' }}>
              <label style={{ display: 'block', marginBottom: '5px' }}>角色:</label>
              <select
                value={editForm.role_id}
                onChange={e => setEditForm({...editForm, role_id: e.target.value})}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #ddd',
                  borderRadius: '4px'
                }}
              >
                <option value="">请选择角色</option>
                {roles.map(role => (
                  <option key={role._id} value={role._id}>
                    {role.name}
                  </option>
                ))}
              </select>
            </div>
            
            <div style={{ marginBottom: '20px' }}>
              <label style={{ display: 'block', marginBottom: '5px' }}>状态:</label>
              <select
                value={editForm.status}
                onChange={(e) => setEditForm({...editForm, status: parseInt(e.target.value)})}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #ddd',
                  borderRadius: '4px'
                }}
              >
                <option value={1}>正常</option>
                <option value={0}>异常</option>
              </select>
            </div>
            
            <div style={{ display: 'flex', gap: '10px', justifyContent: 'flex-end' }}>
              <button
                onClick={handleCloseEditModal}
                style={{
                  padding: '8px 16px',
                  border: '1px solid #ddd',
                  borderRadius: '4px',
                  backgroundColor: '#f5f5f5',
                  cursor: 'pointer'
                }}
              >
                取消
              </button>
              <button
                onClick={handleUpdateUser}
                disabled={loading}
                style={{
                  padding: '8px 16px',
                  border: 'none',
                  borderRadius: '4px',
                  backgroundColor: '#007bff',
                  color: 'white',
                  cursor: loading ? 'not-allowed' : 'pointer',
                  opacity: loading ? 0.6 : 1
                }}
              >
                {loading ? '保存中...' : '保存'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 编辑角色弹窗 */}
      {showRoleEditModal && (
        <div className="modal-overlay" style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          zIndex: 1000
        }}>
          <div className="modal-content" style={{
            backgroundColor: 'white',
            padding: '20px',
            borderRadius: '8px',
            minWidth: '400px',
            maxWidth: '500px'
          }}>
            <h3>编辑角色</h3>
            <div style={{ marginBottom: '15px' }}>
              <label style={{ display: 'block', marginBottom: '5px' }}>角色名称:</label>
              <select
                value={roleEditForm.name}
                onChange={e => setRoleEditForm({ name: e.target.value })}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #ddd',
                  borderRadius: '4px'
                }}
              >
                <option value="">请选择角色名称</option>
                {allRoleNames.map((name: string) => (
                  <option key={name} value={name}>{name}</option>
                ))}
              </select>
            </div>
            {(() => {
              const selectedRole = roles.find(role => role.name === roleEditForm.name);
              if (!selectedRole) return null;
              return (
                <div style={{ marginTop: '10px', background: '#f8f9fa', padding: '10px', borderRadius: '4px' }}>
                  <div>权限数量：{selectedRole.permissions?.length || 0}</div>
                  <div>描述：{selectedRole.description}</div>
                </div>
              );
            })()}
            <div style={{ display: 'flex', gap: '10px', justifyContent: 'flex-end' }}>
              <button
                onClick={handleCloseRoleEditModal}
                style={{
                  padding: '8px 16px',
                  border: '1px solid #ddd',
                  borderRadius: '4px',
                  backgroundColor: '#f5f5f5',
                  cursor: 'pointer'
                }}
              >
                取消
              </button>
              <button
                onClick={handleUpdateRole}
                disabled={loading}
                style={{
                  padding: '8px 16px',
                  border: 'none',
                  borderRadius: '4px',
                  backgroundColor: '#007bff',
                  color: 'white',
                  cursor: loading ? 'not-allowed' : 'pointer',
                  opacity: loading ? 0.6 : 1
                }}
              >
                {loading ? '保存中...' : '保存'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 添加用户弹窗 */}
      {showAddModal && (
        <div className="modal-overlay" style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          zIndex: 1000
        }}>
          <div className="modal-content" style={{
            backgroundColor: 'white',
            padding: '20px',
            borderRadius: '8px',
            minWidth: '400px',
            maxWidth: '500px'
          }}>
            <h3>添加用户</h3>
            <div style={{ marginBottom: '15px' }}>
              <label style={{ display: 'block', marginBottom: '5px' }}>用户名:</label>
              <input
                type="text"
                value={addForm.name}
                onChange={e => setAddForm({ ...addForm, name: e.target.value })}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #ddd',
                  borderRadius: '4px'
                }}
              />
            </div>
            <div style={{ marginBottom: '15px' }}>
              <label style={{ display: 'block', marginBottom: '5px' }}>角色:</label>
              <select
                value={addForm.roles}
                onChange={e => setAddForm({ ...addForm, roles: e.target.value })}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #ddd',
                  borderRadius: '4px'
                }}
              >
                <option value="">请选择角色</option>
                {roles.map(role => (
                  <option key={role._id} value={role.name}>{role.name}</option>
                ))}
              </select>
            </div>
            <div style={{ marginBottom: '20px' }}>
              <label style={{ display: 'block', marginBottom: '5px' }}>状态:</label>
              <select
                value={addForm.status}
                onChange={e => setAddForm({ ...addForm, status: parseInt(e.target.value) })}
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #ddd',
                  borderRadius: '4px'
                }}
              >
                <option value={1}>正常</option>
                <option value={0}>异常</option>
              </select>
            </div>
            <div style={{ marginBottom: '20px' }}>
              <label style={{ display: 'block', marginBottom: '5px' }}>登录时间:</label>
              <input
                type="text"
                value={new Date().toLocaleString('zh-CN')}
                disabled
                style={{
                  width: '100%',
                  padding: '8px',
                  border: '1px solid #ddd',
                  borderRadius: '4px',
                  backgroundColor: '#f5f5f5'
                }}
              />
            </div>
            <div style={{ display: 'flex', gap: '10px', justifyContent: 'flex-end' }}>
              <button
                onClick={handleCloseAddModal}
                style={{
                  padding: '8px 16px',
                  border: '1px solid #ddd',
                  borderRadius: '4px',
                  backgroundColor: '#f5f5f5',
                  cursor: 'pointer'
                }}
              >
                取消
              </button>
              <button
                onClick={handleAddUser}
                disabled={loading}
                style={{
                  padding: '8px 16px',
                  border: 'none',
                  borderRadius: '4px',
                  backgroundColor: '#007bff',
                  color: 'white',
                  cursor: loading ? 'not-allowed' : 'pointer',
                  opacity: loading ? 0.6 : 1
                }}
              >
                {loading ? '保存中...' : '保存'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Authority; 